package main

// 将用户信息用redis队列里面写，赛选出可以匹配的用户

import (
	"hytx_sync/pkg/setting"
	"hytx_sync/models"
	"hytx_sync/pkg/logging"
	"hytx_sync/pkg/gredis"
	"fmt"
	"strconv"

	"github.com/gomodule/redigo/redis"
	"strings"
	"time"
)

var redisConn *redis.Pool

func init() {
	setting.Setup()
	models.Setup()
	logging.Setup()
	gredis.Setup()
	redisConn = gredis.RedisConn
}

func main() {
	UserInterPushInfo := models.UserInterPushInfo{}
	last_id, err := UserInterPushInfo.GetLastId() // 查询匹配列表最后个id
	if err != nil {
		fmt.Println(err)
		return
	}

	conn := redisConn.Get()
	defer conn.Close()
	conn.Do("FLUSHALL")

	var ch = make(chan string)

	// 读取ch
	go pushRedisList(ch)

	// 写入ch
	selectDataPushList(last_id.ID, ch)
}

func selectDataPushList(num int, ch chan string) {

	for i := 1; i <= num; i++ {
		// 查询单个匹配用户
		in := models.UserInterPushInfo{
			ID:        i,
			IsEnabled: 1,
		}
		i_info, err := in.Get()

		if err != nil {
			fmt.Println("没有查询单个匹配用户")
			continue
		}

		model_U_R := models.UserInterPushRecord{
			InterpushId:i_info.UserId,
			IsShare:0, // 未分享
		}
		// 查询主动匹配
		r_info, err := model_U_R.Get()

		// 如果r_info有值
		if r_info != nil {
			fmt.Println("查询主动匹配")
			continue
		}

		model_U_R_P := models.UserInterPushRecord{
			TargetInterpushId:  i_info.UserId,
			TargetIsShare: 0, // 未分享
		}
		// 查询被动匹配
		r_p_info, err := model_U_R_P.GetPassive()

		// 如果r_info有值
		if r_p_info != nil {
			fmt.Println("查询被动匹配")
			continue
		}

		ch <- strconv.Itoa(i_info.ProvinceId) + "-" + strconv.Itoa(i_info.ID) + "-" +  strconv.Itoa(i_info.Num)

	}
}


// 写入redis
func pushRedisList(ch chan string) {

	conn := redisConn.Get()
	defer conn.Close()

	for value := range ch {
		list := strings.Split(value, "-")
		province_id := list[0]
		user_id := list[1]
		num := list[2]

		if int_province_id, _ := strconv.Atoi(province_id); int_province_id != 0 {
			city := time.Now().Format("20060102") + "_" + province_id + "_city"
			conn.Do("SADD", city, user_id)
		}

		// 全国
		quanguo := time.Now().Format("20060102") + "_" + "0" + "_city"
		conn.Do("SADD", quanguo, user_id)

		_, err := conn.Do("set", "user_id_" + user_id, num)

		if err == nil {
			fmt.Println(province_id, user_id, num, "添加成功")
		} else {
			fmt.Println(province_id, user_id, num, "添加失败")
		}
	}


}
